package com.jch.dm4_promise.examples;

import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;

// 角色：Promisor
public class FTPUploadPromisor {

    // 角色功能：Promisor.compute
    public static Future<FTPUploader> newFTPUploaderPromise(String ftpServer,String username,String password,String serverDir){
        Executor helperExecutor = new Executor() {
            @Override
            public void execute(Runnable command) {
                Thread t = new Thread(command);
                t.start();
            }
        };
        return newFTPUploaderPromise(ftpServer,username,password,serverDir,helperExecutor);
    }

    // Promisor.compute
    public static Future<FTPUploader> newFTPUploaderPromise(String ftpServer, String username, String password, String serverDir, Executor helperExecutor) {
        Callable<FTPUploader> callable = new Callable<FTPUploader>() {
            @Override
            public FTPUploader call() throws Exception {
                String implClass = System.getProperty("ftp.client.impl");
                if (null == implClass){
                    implClass = "com.jch.dm4_promise.examples.FTPClientUtil";
                }
                FTPUploader ftpUploader = (FTPUploader) Class.forName(implClass).newInstance();
                ftpUploader.init(ftpServer,username,password,serverDir);
                return ftpUploader;
            }
        };
        // 角色：Promise
        final FutureTask<FTPUploader> task = new FutureTask<>(callable);
        helperExecutor.execute(task);
        return task;
    }

}
